//
//  SNSearchView.m
//  ZhuoxinAgriculture
//
//  Created by stone on 16/12/16.
//  Copyright © 2016年 stone. All rights reserved.
//

#import "SNProductionSearchHistoryManager.h"
#import "SNProductionSearchViewNext.h"
#import "UIImageView+TapGesture.h"
@interface SNProductionSearchViewNext()<UITextFieldDelegate>
/** tapEnable */
@property (nonatomic, assign,getter=isTapEnable) BOOL tapEnable;

/** imageView */
@property (weak, nonatomic) UIImageView * textFieldImageView;
@end
@implementation SNProductionSearchViewNext

- (instancetype)initWithFrame:(CGRect)frame tapEnable:(BOOL)tapEnable
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = HexRGB(0xf5f5f5);
        _tapEnable = tapEnable;
        [self addViews:frame];
        [self setupUI];
        
    }
    return self;
}
- (void)addViews:(CGRect)frame
{
    CGSize size = [[[NSAttributedString alloc] initWithString:@"取消" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:15]}] boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading context:nil].size;
    
    UILabel * titleLabel = ({
        UILabel * label = [[UILabel alloc] init];
        /** GPU 优化 */
        //        label.opaque = YES;
        //        label.backgroundColor = [UIColor whiteColor];
        //        label.layer.masksToBounds = YES;
        //------------------------------
        label.numberOfLines = 0;
        label.textColor = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"取消";
        label.font = [UIFont systemFontOfSize:15];
        
        label.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - 15 - size.width-10, 0, size.width+15+10, frame.size.height);
        [self addSubview:label];
        label.sn_tapBlock = ^(){
            !self.siftBlock ?: self.siftBlock();
        };
        label;
    });
    self.titleLabel = titleLabel;
    
    
    if (self.tapEnable) {
        UITextField * textField = ({
            
            UITextField * textField = [[UITextField alloc] init];
            textField.delegate = self;
            textField.font = [UIFont systemFontOfSize:15];
            textField.borderStyle = UITextBorderStyleRoundedRect;
            textField.backgroundColor = [UIColor whiteColor];
            textField.placeholder = @"搜索姓名/手机号码";
            UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 32, frame.size.height - 10)];
            {
                UIImageView * imageView = [[UIImageView alloc] init];
                UIImage * image = [UIImage imageNamed:@"icon_search"];
                imageView.image = image;
                
                imageView.frame = CGRectMake(13, (frame.size.height - 10 - 14)*0.5, 14, 14);
                [leftView addSubview:imageView];
                
            }
            textField.leftView = leftView;
            textField.clearButtonMode = UITextFieldViewModeWhileEditing;
            textField.leftViewMode = UITextFieldViewModeUnlessEditing;
            textField.frame = CGRectMake(11, 5, titleLabel.frame.origin.x - 11, frame.size.height - 10);
            textField.returnKeyType = UIReturnKeySearch;
            
            [self addSubview:textField];
            
            //  [self foo:textField];
            
            textField;
        });
        self.textField = textField;
        
    }
}

- (void)foo:(UITextField *)textField
{
    CGSize size = textField.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    [textField.layer renderInContext:context];
    
    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    //	UIImageWriteToSavedPhotosAlbum(newImage, NULL, NULL, NULL);
    NSData * data = UIImagePNGRepresentation(newImage);
    [data writeToFile:@"/Users/stone/Desktop/aaa.png" atomically:YES];
    
    UIGraphicsEndImageContext();
}
- (void)setupUI
{
    
}

#pragma mark - <UITextFieldDelegate>
//sn_note:========= UITextFieldDelegate ============================ stone 🐳 ===========/
//// return NO to disallow editing.
//- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
//    return YES;
//}
//// became first responder
//- (void)textFieldDidBeginEditing:(UITextField *)textField{
//
//}
//// return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
//- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
//    return YES;
//}
//// may be called if forced even if shouldEndEditing returns NO (e.g. view removed from window) or endEditing:YES called
//- (void)textFieldDidEndEditing:(UITextField *)textField{
//
//}
//// if implemented, called in place of textFieldDidEndEditing:
//- (void)textFieldDidEndEditing:(UITextField *)textField reason:(UITextFieldDidEndEditingReason)reason NS_AVAILABLE_IOS(10_0){
//
//}
//// return NO to not change text
//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    return YES;
//}
//// called when clear button pressed. return NO to ignore (no notifications)
//- (BOOL)textFieldShouldClear:(UITextField *)textField{
//    return YES;
//}
// called when 'return' key pressed. return NO to ignore.
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    NSString * string = [textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    SNProductionSearchHistoryModel * findModel = [SNProductionSearchHistoryModel findFirstByCriteria:[NSString stringWithFormat:@"WHERE searchText = '%@'",string]];
    if (findModel) {
        // 有就摆到最前面去
        //TODO: 有就摆到最前面去
        !self.reloadDataCollectionView ?: self.reloadDataCollectionView(string);
    }else{
        SNProductionSearchHistoryModel * model = [SNProductionSearchHistoryModel new];
        model.searchText = string;
        if (string.length>0) {
            
            [[SNProductionSearchHistoryManager sharedManager] addObject:model];
        }
        
        !self.reloadDataCollectionView ?: self.reloadDataCollectionView(string);
    }
    
    return YES;
}
@end
